package com.yulebaby.callsenter.ui.base;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.yulebaby.callsenter.ui.view.StateViewLayout;

import java.util.List;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * Author: Zhangbo
 * Time: 2016年11月8日
 */

public abstract class BasicFragment extends BaseFragment implements StateViewLayout.OnReloadBtnClickListener, EasyPermissions.PermissionCallbacks {
    protected StateViewLayout mStateViewLayout;
    public Context mContext;
    protected LayoutInflater mInflater;
    private Unbinder mUnbinder;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = getContext();
        mInflater = LayoutInflater.from(context);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (mStateViewLayout == null) {
            mStateViewLayout = new StateViewLayout(mActivity);
            mStateViewLayout.setSuccessView(getSuccessView());
            mStateViewLayout.showLoadingView();
            mStateViewLayout.setOnReloadClickListener(this);
            requestData();
        } else {
            ViewGroup parent = (ViewGroup) mStateViewLayout.getParent();
            if (parent != null) {
                parent.removeView(mStateViewLayout);
            }
        }
        mUnbinder = ButterKnife.bind(this, mStateViewLayout);
        return mStateViewLayout;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onReloadBtnClick() {
        mStateViewLayout.showLoadingView();
        requestData();
    }

    /**
     * 返回成功的View
     */
    public abstract View getSuccessView();

    /**
     * 数据加载
     */
    public abstract void requestData();

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mUnbinder.unbind();
    }
}
